<%@page import="com.huynhchihieu.controller.Constant"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib tagdir="/WEB-INF/tags" prefix="cesc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Book</title>
<link href="<c:url value="/resources/css/jquery-ui.css" />"
	rel="stylesheet" type="text/css" />
<link href="<c:url value="/resources/css/jquery-ui.theme.css" />"
	rel="stylesheet" type="text/css" />
<link href="<c:url value="/resources/css/jquery-ui.structure.css" />"
	rel="stylesheet" type="text/css" />
<link href="<c:url value="/resources/css/table.css" />" rel="stylesheet"
	type="text/css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/jqgrid/ui.jqgrid.css" />
        <link rel="stylesheet" type="text/css" href='<c:url value="/resources/css/slider/demo.css" />'/>
		<link rel="stylesheet" type="text/css" href='<c:url value="/resources/css/slider/style.css" />'/>
		<link rel="stylesheet" type="text/css" href='<c:url value="/resources/css/slider/elastislide.css" />' />
		<!-- <noscript>
			<style>
				.es-carousel ul{
					display:block;
				}
			</style>
		</noscript> -->
	
<script type="text/javascript"
	src='<c:url value="/resources/js/jquery-1.11.1.js" />'></script>
<script type="text/javascript"
	src='<c:url value="/resources/js/jquery-ui.js" />'></script>
<script src="js/jqgrid/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jqgrid/jquery.jqGrid.min.js" type="text/javascript"></script>
	<script id="img-wrapper-tmpl" type="text/x-jquery-tmpl">	
			<div class="rg-image-wrapper">
				{{if itemsCount > 1}}
					<div class="rg-image-nav">
						<a href="#" class="rg-image-nav-prev">Previous Image</a>
						<a href="#" class="rg-image-nav-next">Next Image</a>
					</div>
				{{/if}}
				<div class="rg-image"></div>
				<div class="rg-loading"></div>
				<div class="rg-caption-wrapper">
					<div class="rg-caption" style="display:none;">
						<p></p>
					</div>
				</div>
			</div>
		</script>
<script type="text/javascript">

	$(document)
			.ready(
					function() {
						// payload get data and show table data
						$.ajax({
								  type: "POST",
 								  /*dataType : The type of data that you're expecting back from the server
 								  . If none is specified, jQuery will try to infer it based 
 								  on the MIME type of the response (an XML MIME type will yield XML,
 										  in 1.4 JSON will yield a JavaScript object */
								  dataType: 'json',
								  contentType: "application/json; charset=utf-8",
								  url: "${pageContext.request.contextPath}/getAllBooks",
								  cache: false,    
								  //data : JSON.stringify(json),
								  success: function(response){
									  addDataTable(response);
								  },
								  error: function(e, status, aa){      
								   alert('Error while request..');
								  }
							 });
						// auto-complete
						     $( "#automplete-1" ).autocomplete({
						    	 source: function(request, response) {
								    	        $.getJSON('${pageContext.request.contextPath}/getTags', { term: request.term }, function(result) {
								    	            response($.map(result, function(item) {
								    	                return item.bookName;
								    	            }));
								    	        });
						    	    	},
						        });
						
						$('#clearcached').click(
								function() {
									$('#formmain').attr('action',
											'/MavenExample/clearCached')
											.submit();
								});
						// set auto open dialog is false
						$("#dialog").dialog({
							autoOpen : false
						});
	$('#dialog').dialog({
							height : 200,
							width : 1000,
							modal : true,
							resizable : true,
							bgiframe : true,
							dialogClass : 'no-close success-dialog'
						});
	
						$('#logout').click(function() {
							$('#logoutForm').submit();
						});
						
					});


	
	function edit(id, name, author, category, numpages, price) {
		// set eventType 
		$('#dialogForm').append('<input type="hidden" name="event_type" value="<%= Constant.UPDATE %>" />');
		// load entity need changed
		$('#idChange').val(id);
		$('#nameChange').val(name);
		$('#authorChange').val(author);
		$('#categoryChange').val(category);
		$('#numpagesChange').val(numpages);
		$('#priceChange').val(price);
		//set title
		$("#dialog").dialog("option", "title", "Edit Book");
		// open dialog
		$("#dialog").dialog("open");

	}

	function createBook() {
		// set eventType
		$('#dialogForm').append('<input type="hidden" name="event_type" value="<%= Constant.CREATE %>" />');
		// dm cho nay no hanh minh sang gio 
		$('#idChange').val(0);
		$('#nameChange').val('');
		$('#authorChange').val('');
		$('#categoryChange').val('');
		$('#numpagesChange').val(0);
		$('#priceChange').val(0);
		//set title
		$("#dialog").dialog("option", "title", "Create Book");
		// open dialog
		$("#dialog").dialog("open");

	}
	function searchBook(){
		$.ajax({
			  type: "GET",
			  dataType: 'json',
			  //contentType: "application/json; charset=utf-8",
			  contentType: false,
			  url: "${pageContext.request.contextPath}/findBooks",
			  data: { 'bookName' : $('#automplete-1').val() },
			  success: function(response){
				  addDataTable(response);
			  },
			  error: function(e, status, aa){      
			   alert('Error while request..');
			  }
		});
	}
	
	function deleteRecord(id) {
		$("#dialog-confirm").html("Do you want to delete this record?");
		$("#dialog-confirm").dialog(
				{
					resizable : true,
					modal : true,
					title : "Confirm Dialog",
					height : 250,
					width : 400,
					buttons : {
						"Yes" : function() {
							$(this).dialog('close');
							// only submit contentType is json not the same with search?? 
							$.ajax({
								  type: "POST",
								  dataType: 'json',
								  contentType: "application/json; charset=utf-8",
								  url: "${pageContext.request.contextPath}/deleteRecord", 
								  data: JSON.stringify({ 'id' : id }),
								  success: function(response){
									  addDataTable(response);
								  },
								  error: function(e, status, content){      
								   alert('Error while request..');
								  }
							});
						},
						"No" : function() {
							$(this).dialog('close');
						}
					}
				});
	}
	// ajax submit
	function upDateBook(){
		var formdata = new FormData();
		var imgfileList = $('#imagesChange').prop('files');
		if (imgfileList && imgfileList != null && imgfileList.length > 0) {
		    formdata.append('filename', imgfileList[0]);
		}
		var other_data = $('#dialogForm :input').serializeArray();
		$.each( other_data, function( key, value ) {
			formdata.append( value.name,  value.value );
			});
		
		 $.ajax({
		  type: "POST",
		  //dataType is what you're expecting back from the server
		  dataType: 'json',
		  //contentType is the type of data you're sending
		 //contentType: "application/json; charset=utf-8",
		 mimeType:"multipart/form-data",
		 processData: false,
		 contentType: false,
		  url: "${pageContext.request.contextPath}/updateBook",
		  cache: false,    
		  data : formdata,
		  success: function(response){
			  addDataTable(response);
		  },
		  error: function(e, status, aa){      
		   alert('Error while request..');
		  }
		 });
		 
		 $('#dialog').dialog('close');
		}
	
	function addDataTable(data){
		<% String rootPath = System.getProperty("catalina.home"); %>
		  // clear content div
		  $('#container').empty();
		  
			// add heading
			$('#container').append('<div class="heading" id="heading_main"></div>');
			$('#heading_main').append('<div class="col">book_id</div>');
			$('#heading_main').append('<div class="col">book_name</div>');
			$('#heading_main').append('<div class="col">book_author</div>');
			$('#heading_main').append('<div class="col">category</div>');
			$('#heading_main').append('<div class="col">numpages</div>');
			$('#heading_main').append('<div class="col">price</div>');
			$('#heading_main').append('<div class="col">images</div>');
			$('#heading_main').append('<div class="col">modification</div>');
			var index;
			var length = data.length;
			// add data for div container
			for(index = 0; index<=length; index++){
			
				// add table-row
				$('#container').append('<div class="table-row" id="'+'table-row'+index+ '"></ div>');
				// bookId
				$('#'+'table-row'+index).append('<div class="col">'+data[index].bookId+'</div>');
				// bookAuthor
				$('#'+'table-row'+index).append('<div class="col">'+data[index].bookName+'</div>');
				// bookName
				$('#'+'table-row'+index).append('<div class="col">'+data[index].bookAuthor+'</div>');
				// category
				$('#'+'table-row'+index).append('<div class="col">'+data[index].category+'</div>');
				// numpages
				$('#'+'table-row'+index).append('<div class="col">'+data[index].numpages+'</div>');
				// price
				$('#'+'table-row'+index).append('<div class="col">'+data[index].price+'</div>');
				// images <img alt="title" src="${catalina.home}/">
// 				$('#'+'table-row'+index).append('<div class="col"><img alt="" src="/resources/images/'+ data[index].images+'" /></div>');
				$('#'+'table-row'+index).append('<div class="col"><img alt="" height="42" width="42" src="<c:url value="/resources/images/'+ data[index].images+'" />" /></div>');
				// modification
				$('#'+'table-row'+index).append('<div class="col">' +
					'<u class="edit"' + 
						'onclick="edit('+ "'"+data[index].bookId+ "'" +
				',' + "'"+data[index].bookName+ "'" + 
				',' + "'" +data[index].bookAuthor+ "'" +
				','+ "'" +data[index].category+ "'" +
				','+ "'"+ data[index].numpages+ "'" + 
				','+ "'" + data[index].price+ "'" + ')">' +
						'Edit </u> &nbsp; <u class="delete" onclick="deleteRecord(' + "'"+data[index].bookId+ "'" + ')">Delete</u></div>');
			
			}
		 
	}
	
</script>
</head>
<!--  modelAttribute="books" -->
<body>
	<div id="topmain">
		<c:url value="/j_spring_security_logout" var="logoutUrl" />
		<!-- csrt for log out-->
		<form:form action="${logoutUrl}" method="post" id="logoutForm">
			<input type="hidden" name="${_csrf.parameterName}"
				value="${_csrf.token}" />
		</form:form>
		<c:if test="${pageContext.request.userPrincipal.name != null}">
		
			Welcome : ${pageContext.request.userPrincipal.name} | <a id="logout">
				Logout</a>

		</c:if>
	</div>
	<div id="dialog-confirm"></div>
	<div id="dialog">
		<form:form action='/MavenExample/books' method="get"
			 id="dialogForm" enctype="multipart/form-data">
			<input type="hidden" id="eventTypeDialogFrom" name="" />
			<div class="container" >
				<div class="heading">
					<!-- 					<div class="col">book_id</div> -->
					<div class="col">book_name</div>
					<div class="col">book_author</div>
					<div class="col">category</div>
					<div class="col">numpages</div>
					<div class="col">price</div>
					<div class="col">images</div>
				</div>
				<div class="table-row">
					<!-- 					<div class="col"> -->
					<input type="hidden" id="idChange" name="idChange"/>
					<!-- 					</div> -->
					<div class="col">
						<input type="text" id="nameChange" name="nameChange"/>
					</div>
					<div class="col">
						<input type="text" id="authorChange" name="authorChange" />
					</div>
					<div class="col">
						<input type="text" id="categoryChange" name="categoryChange" />
					</div>
					<div class="col">
						<input type="text" id="numpagesChange" name="numpagesChange"/>
					</div>
					<div class="col">
						<input type="text" id="priceChange" name="priceChange" />
					</div>
					<div class="col">
						<input type="file" id="imagesChange" name="file"/>
					</div>
				</div>
			</div>
			<input id="save" type="button" value="SaveBook" onclick="upDateBook()">
		</form:form>
	</div>
	<div>
		<form:form method="GET" id="formmain" action="/MavenExample/books">
			<div class="nav">
				<input type="hidden" id="idRecord" name="idRecord" value="">
				<input type="text" name="bookName" id="automplete-1"/>
				 <input type="button"
					value="Search Book" id="search" onclick="searchBook()"/>
					 <input type="button"
					value="Add Book" id="addBook" onclick="createBook()" /> 
					<input
					type="button" value="Clear Cached" id="clearcached" />
			</div>
			<div class="container" id="container">
<!-- 				<div class="heading"> -->
<!-- 					<div class="col">book_id</div> -->
<!-- 					<div class="col">book_name</div> -->
<!-- 					<div class="col">book_author</div> -->
<!-- 					<div class="col">category</div> -->
<!-- 					<div class="col">numpages</div> -->
<!-- 					<div class="col">price</div> -->
<!-- 					<div class="col">modification</div> -->
<!-- 				</div> -->
<%-- 				<c:forEach items="${books }" var="book"> --%>
<!-- 					<div class="table-row"> -->
<!-- 						<div class="col"> -->
<%-- 							<c:out value="${book.bookId }" /> --%>
<!-- 						</div> -->
<!-- 						<div class="col"> -->
<%-- 							<c:out value="${book.bookName }" /> --%>
<!-- 						</div> -->
<!-- 						<div class="col"> -->
<%-- 							<c:out value="${book.bookAuthor }" /> --%>
<!-- 						</div> -->
<!-- 						<div class="col"> -->
<%-- 							<c:out value="${book.category }" /> --%>
<!-- 						</div> -->
<!-- 						<div class="col"> -->
<%-- 							<c:out value="${book.numpages }" /> --%>
<!-- 						</div> -->
<!-- 						<div class="col"> -->
<%-- 							<c:out value="${book.price }" /> --%>
<!-- 						</div> -->
<!-- 						<div class="col"> -->
<!-- 							<u class="edit" -->
<%-- 								onclick="edit('${book.bookId }', '${book.bookName }', '${book.bookAuthor }' --%>
<%-- 						, '${book.category }'  --%>
<%-- 						, '${book.numpages }'  --%>
<%-- 						, '${book.price }')">  --%>
<!--  								Edit </u> &nbsp; <u class="delete" -->
<%-- 								onclick="deleteRecord('${book.bookId }')">Delete</u> --%>
<!-- 						</div> -->
<!-- 					</div> -->
<%-- 				</c:forEach> --%>
			</div>
		</form:form>
	</div>
	<cesc:slider></cesc:slider>
</body>
</html>